<template>
  <div class="plasma-bg">
    <canvas ref="canvasRef"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvasRef = ref(null)
let animationId = null

onMounted(() => {
  const canvas = canvasRef.value
  const ctx = canvas.getContext('2d')
  
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight

  let time = 0

  const plasma = (x, y, time) => {
    return (
      Math.sin(x * 0.02 + time) +
      Math.sin(y * 0.02 + time) +
      Math.sin((x + y) * 0.02 + time) +
      Math.sin(Math.sqrt(x * x + y * y) * 0.02 + time)
    )
  }

  const draw = () => {
    const imageData = ctx.createImageData(canvas.width, canvas.height)
    const data = imageData.data

    for (let y = 0; y < canvas.height; y += 2) {
      for (let x = 0; x < canvas.width; x += 2) {
        const value = plasma(x, y, time)
        const color = Math.floor(((value + 4) / 8) * 255)
        
        // 创建彩色等离子效果
        const index = (y * canvas.width + x) * 4
        data[index] = Math.floor(Math.sin(value + time) * 127 + 128)       // R
        data[index + 1] = Math.floor(Math.sin(value + time + 2) * 127 + 128) // G
        data[index + 2] = Math.floor(Math.sin(value + time + 4) * 127 + 128) // B
        data[index + 3] = 255 // A

        // 填充相邻像素
        if (x + 1 < canvas.width) {
          data[index + 4] = data[index]
          data[index + 5] = data[index + 1]
          data[index + 6] = data[index + 2]
          data[index + 7] = 255
        }
        if (y + 1 < canvas.height) {
          const nextRowIndex = ((y + 1) * canvas.width + x) * 4
          data[nextRowIndex] = data[index]
          data[nextRowIndex + 1] = data[index + 1]
          data[nextRowIndex + 2] = data[index + 2]
          data[nextRowIndex + 3] = 255
        }
      }
    }

    ctx.putImageData(imageData, 0, 0)
    
    time += 0.05
    animationId = requestAnimationFrame(draw)
  }

  draw()

  const handleResize = () => {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
  }

  window.addEventListener('resize', handleResize)

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (animationId) {
      cancelAnimationFrame(animationId)
    }
  })
})
</script>

<style scoped>
.plasma-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #000;
}

canvas {
  display: block;
}
</style>

